package com.lwj.liwanjia.view.activity.supermarket;


import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.lwj.liwanjia.MainActivity;
import com.lwj.liwanjia.R;
import com.lwj.liwanjia.adapter.LeftListAdapter;
import com.lwj.liwanjia.adapter.MainSectionedAdapter;
import com.lwj.liwanjia.base.BaseActivity;
import com.lwj.liwanjia.bean.MarketFDBean;
import com.lwj.liwanjia.bean.MarketFenleiBean;
import com.lwj.liwanjia.config.OnItemClickListener;
import com.lwj.liwanjia.impl.MarketFDView;
import com.lwj.liwanjia.impl.MarketleftView;
import com.lwj.liwanjia.presenter.MarketFDetailPresenter;
import com.lwj.liwanjia.presenter.MarketShangpinPresenter;
import com.lwj.liwanjia.utils.MyGridView;
import com.lwj.liwanjia.utils.NetWorkUtil;
import com.lwj.liwanjia.utils.PinnedHeaderListView;
import com.lwj.liwanjia.utils.SpfUtils;
import com.lwj.liwanjia.view.activity.login.LoginActivity;
import com.lwj.liwanjia.view.activity.search.SearchActivity;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 利万嘉超市
 */
public class MarketActivity extends BaseActivity implements MarketleftView, MarketFDView {

    @BindView(R.id.market_back)
    TextView marketBack;
    @BindView(R.id.tv_search)
    TextView tvSearch;
    @BindView(R.id.gouwuche_number)
    TextView number;            //当前购物车中物品数量
    @BindView(R.id.market_search)
    RelativeLayout marketSearch;
    @BindView(R.id.left_listview)
    ListView leftListview;
    @BindView(R.id.pinnedListView)
    PinnedHeaderListView pinnedListView;
    @BindView(R.id.progress)
    ProgressBar progressBar;

    private boolean isScroll = true;
    private LeftListAdapter adapter;
    private MainSectionedAdapter sectionedAdapter;

    private List<String> leftList = new ArrayList<>();
    private List<Boolean> flagArray = new ArrayList<>();//左侧选中
    private List<MarketFDBean.DataBean> list = new ArrayList<>();
    private MarketShangpinPresenter shagnpinPresenter;
    private SpfUtils spfUtils;
    private int shopInfoId;
    private String supType;
    private MarketFDetailPresenter marketFDetailPresenter;

    @Override
    protected void initView() {
        shopInfoId = getIntent().getIntExtra("shopInfoId", 0);
        supType = getIntent().getStringExtra("supType");
        adapter = new LeftListAdapter(this, leftList, flagArray);
        sectionedAdapter = new MainSectionedAdapter(this, list);
        pinnedListView.setAdapter(sectionedAdapter);
        View rightHeader = LayoutInflater.from(this).inflate(R.layout.left_header_item, null);
        leftListview.addHeaderView(rightHeader, null, false);
        leftListview.setAdapter(adapter);
        shagnpinPresenter = new MarketShangpinPresenter(this);
        marketFDetailPresenter = new MarketFDetailPresenter(this);
        spfUtils = SpfUtils.getSpfUtils(this);
        number.setText(spfUtils.getGwcNumber() + "");
        clickListener();
    }

    //监听事件
    private void clickListener() {
        leftListview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> arg0, View view, int position, long arg3) {
                isScroll = false;

                for (int i = 0; i < list.size(); i++) {
                    if (i == position - 1) {
                        flagArray.add(i, true);
                    } else {
                        flagArray.add(i, false);
                    }
                }
                adapter.notifyDataSetChanged();
                int rightSection = 0;
                for (int i = 0; i < position - 1; i++) {
                    rightSection += sectionedAdapter.getCountForSection(i) + 1;
                }
                pinnedListView.setSelection(rightSection);
            }
        });
        pinnedListView.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView arg0, int scrollState) {
                switch (scrollState) {
                    // 当不滚动时
                    case AbsListView.OnScrollListener.SCROLL_STATE_IDLE:
                        // 判断滚动到底部
                        if (pinnedListView.getLastVisiblePosition() == (pinnedListView.getCount() - 1)) {
                            leftListview.setSelection(ListView.FOCUS_DOWN);
                        }

                        // 判断滚动到顶部
                        if (pinnedListView.getFirstVisiblePosition() == 0) {
                            leftListview.setSelection(0);
                        }

                        break;
                }
            }

            int y = 0;
            int x = 0;
            int z = 0;

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                if (isScroll) {
                    for (int i = 0; i < list.size(); i++) {
                        if (i == sectionedAdapter.getSectionForPosition(pinnedListView.getFirstVisiblePosition())) {
                            flagArray.add(i, true);
                            x = i;
                        } else {
                            flagArray.add(i, false);
                        }
                    }
                    if (x != y) {
                        adapter.notifyDataSetChanged();
                        y = x;
                        //左侧ListView滚动到最后位置
                        if (y == leftListview.getLastVisiblePosition()) {
                            leftListview.setSelection(z);
                        }
                        //左侧ListView滚动到第一个位置
                        if (x == leftListview.getFirstVisiblePosition()) {
                            leftListview.setSelection(z);
                        }
                        if (firstVisibleItem + visibleItemCount == totalItemCount - 1) {
                            leftListview.setSelection(ListView.FOCUS_DOWN);
                        }
                    }
                } else {
                    isScroll = true;
                }
            }
        });
        sectionedAdapter.setListener(new OnItemClickListener() {
            @Override
            public void OnItemClick(View view, final int section) {
                MyGridView gridView = (MyGridView) view;
                gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                        Intent intent = new Intent(MarketActivity.this, ShangPinActivity.class);
                        Bundle bundle = new Bundle();
                        bundle.putString("type", list.get(section).getGoodsType().get(position).getName());
                        bundle.putInt("shopInfoId ", shopInfoId);
                        intent.putExtras(bundle);
                        startActivity(intent);
                    }
                });
            }
        });
    }

    @Override
    protected void initData() {
        shagnpinPresenter.getMarkeShangpin( shopInfoId, supType);
        marketFDetailPresenter.getMarkFDetail( shopInfoId, supType);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_market;
    }

    @OnClick({R.id.market_gouwuche, R.id.market_search, R.id.market_back})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.market_back:
                finish();
                break;
            case R.id.market_gouwuche://购物车
                Intent intent = new Intent(MarketActivity.this, MainActivity.class);
                intent.putExtra("type", "购物车");
                startActivity(intent);
                finish();
                break;
            case R.id.market_search://搜索
                startActivity(new Intent(this, SearchActivity.class));
                break;
        }
    }

    @Override
    public void showProgress() {
        progressBar.setVisibility(View.VISIBLE);
    }

    @Override
    public void hideProgress() {
        progressBar.setVisibility(View.GONE);
    }

    @Override
    public void showError(Exception e) {
        Toast.makeText(this, "数据加载失败！", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void getMarketFDDetail(MarketFDBean marketFDBean) {
      if (marketFDBean.getState() == 1) {
            list.clear();
            list.addAll(marketFDBean.getData());
            sectionedAdapter.notifyDataSetChanged();
        }
    }

    @Override
    public void getMarketData(MarketFenleiBean marketFenleiBean) {
        if (marketFenleiBean.getState() == 1) {
            leftList.clear();
            leftList.addAll(marketFenleiBean.getData());
            for (int i = 0; i < marketFenleiBean.getData().size(); i++) {
                if (i == 0) {
                    flagArray.add(i, true);
                } else {
                    flagArray.add(i, false);
                }
            }
            adapter.notifyDataSetChanged();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (shagnpinPresenter != null) {
            shagnpinPresenter = null;
        }
        if (marketFDetailPresenter != null) {
            marketFDetailPresenter = null;
        }
    }
}
